#!/usr/bin/python
# -*- coding:UTF-8 -*-
# @Time    : 2019/1/9 16:39
# @Author  : 王志鹏
# @Site    : 
# @File    : d1.py
# @Software: PyCharm

"""
享元模式 Flyweight: 运用共享技术有效的支持大量细粒度的对象
享元模式可以避免大量非常相似类的开销.在程序设计中有时需要生成大量细粒度的类实例来表示数据,如果发现这几个类除了几个参数外都是相同的
有时就能够大量的减少需要实例化类的数量,如果能把那些参数转移到类实例的外面,在方法调用时给他们传进来,就可以通过共享大幅度减少单个实例的数目

享元模式的应用:
    如果一个程序使用了大量的对象,而大量的这写对象造成了很大的储存开销是就应该考虑使用;还有就是对象的大多数状态可以外部状态,若果删除对象的外部状态
    那么久可以用相对较少的共享对象取代很多组对象,此时应该考虑使用享元模式
"""

import abc


class Flyweight(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def Operation(self, extrinsicstate): pass


# 享元工厂 管理具体的享元对象
class FlyweightFactory(object):
    def __init__(self):
        self.flyweights = {}
        self.flyweights["X"] = ConcreteFlyweight()
        self.flyweights["Y"] = ConcreteFlyweight()
        self.flyweights["Z"] = ConcreteFlyweight()

    def getFlyweight(self, keyName):
        return self.flyweights[keyName]


class ConcreteFlyweight(Flyweight):
    def Operation(self, extrinsicstate):
        print "具体的Flyweight %s" % extrinsicstate


class UnsharedConcreteFlyweight(Flyweight):
    def Operation(self, extrinsicstate):
        print "不共享具体的Flyweight %s" % extrinsicstate


if __name__ == '__main__':
    extrinsicstate = 22  # 代码外部状态

    f = FlyweightFactory()

    fx = f.getFlyweight("X")
    extrinsicstate -= 1
    fx.Operation(extrinsicstate)

    fy = f.getFlyweight("Y")
    extrinsicstate -= 1
    fy.Operation(extrinsicstate)

    fz = f.getFlyweight("Z")
    extrinsicstate -= 1
    fz.Operation(extrinsicstate)

    uf = UnsharedConcreteFlyweight()
    extrinsicstate -= 1
    uf.Operation(extrinsicstate)
